//
//  LivePlayViewController.m
//  Runner
//
//  Created by 小二同學 on 2020/3/17.
//  Copyright © 2020 The Chromium Authors. All rights reserved.
//

#import "LivePlayViewController.h"
//#import <AliyunPlayer/AliyunPlayer.h>
#import "LivePlaySlider.h"
#import "ZJScrollPageView.h"
#import "PlayInfoViewController.h"
#import "PlayChatViewController.h"
#import <NELivePlayerFramework/NELivePlayerFramework.h>

//[UIScreen mainScreen].bounds.size.width * 9/16

NSString *const ZJParentTableViewDidLeaveFromTopNotification = @"ZJParentTableViewDidLeaveFromTopNotification";


@interface ZJCustomGestureTableView : UITableView

@end

@implementation ZJCustomGestureTableView

/// 返回YES同时识别多个手势
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    return [gestureRecognizer isKindOfClass:[UIPanGestureRecognizer class]] && [otherGestureRecognizer isKindOfClass:[UIPanGestureRecognizer class]];
}
@end

@interface LivePlayViewController ()<UIGestureRecognizerDelegate,ZJScrollPageViewDelegate, UIScrollViewDelegate>

//@property (nonatomic, strong) AliPlayer *aliPlayer;               //点播播放器
@property (nonatomic, strong) NELivePlayerController *player; //播放器sdk
@property (nonatomic, strong) UIView *playerView;
@property (nonatomic, strong) UIImageView *playerImage;
@property (nonatomic, strong) UIView *playerBackView;
@property (nonatomic, strong) UILabel *playerName;
@property (nonatomic, strong) UILabel *playerTime;
@property (nonatomic, strong) UIButton *popButton;
@property (nonatomic, strong) UIActivityIndicatorView * activityIndicator;
@property (nonatomic, strong) UIButton *popButtonBig;

@property (nonatomic, strong) UIView *bottomView;
@property (nonatomic, strong) UIButton *bgView;
@property (nonatomic, strong) UILabel *timeLabel;
@property (nonatomic, strong) UIButton *pauseButton;
@property (nonatomic, strong) LivePlaySlider *slider;
@property (nonatomic, strong) UIButton *screenButton;
@property (nonatomic, strong) UIButton *screenButtonBig;

@property (nonatomic, strong) UIButton *returnBUtton;

@property (nonatomic, assign) BOOL progressSilderTouching;

@property (nonatomic,strong) NSTimer *timer; // 计时器 3s之后隐藏进度条

@property(strong, nonatomic)NSArray<NSString *> *titles;
@property(strong, nonatomic)NSArray<UIViewController *> *childVcs;
@property (nonatomic, strong) ZJScrollPageView *scrollPageView;

@property (nonatomic, strong) NSDictionary *playInfo;

@property (nonatomic,strong) NSTimer *durrTimer; // 播放进度
@property (nonatomic,assign) int sec; // 播放进度
@end

@implementation LivePlayViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor blackColor];
    [[UIApplication sharedApplication] setIdleTimerDisabled:YES];
            
    UITapGestureRecognizer *singleTapGestureRecognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hideProessBar:)];
    [singleTapGestureRecognizer setNumberOfTapsRequired:1];
    singleTapGestureRecognizer.delegate = self;
    [self.playerView addGestureRecognizer:singleTapGestureRecognizer];

    UITapGestureRecognizer *doubleTapGestureRecognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(TapPlayAndStop:)];
    doubleTapGestureRecognizer.delegate = self;
    [doubleTapGestureRecognizer setNumberOfTapsRequired:2];
    [self.playerView addGestureRecognizer:doubleTapGestureRecognizer];
    [singleTapGestureRecognizer requireGestureRecognizerToFail:doubleTapGestureRecognizer];
        
    [self.playerView addSubview:self.bgView];
//    [self.playerView addSubview:self.popButton];
//    [self.playerView addSubview:self.popButtonBig];
    
//    [self.playerView addSubview:self.returnBUtton];
    [self.bgView addSubview:self.pauseButton];
    [self.bottomView addSubview:self.slider];
    [self.bottomView addSubview:self.screenButton];
    [self.bottomView addSubview:self.timeLabel];
    [self.playerView addSubview:self.activityIndicator];
//    [self.playerView addSubview:self.returnBUtton];
    
    [self.view addSubview:self.playerImage];
    [self.playerImage addSubview:self.playerBackView];
    [self.playerBackView addSubview:self.playerName];
    [self.playerBackView addSubview:self.playerTime];
    
    //必要的设置, 如果没有设置可能导致内容显示不正常
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    ZJSegmentStyle *style = [[ZJSegmentStyle alloc] init];
    //显示滚动条
    style.showLine = YES;
    // 颜色渐变
    style.gradualChangeTitleColor = YES;
    style.scrollLineColor = UIColorFromRGB(0xFF1a73e8);
    style.selectedTitleColor = UIColorFromRGB(0xFF1a73e8);
    style.normalTitleColor = UIColorFromRGB(0xff333333);
    style.titleFont = [UIFont systemFontOfSize:16];
    style.scrollTitle = NO;
    
    // 初始化
    _scrollPageView = [[ZJScrollPageView alloc] initWithFrame:CGRectMake(0, ([UIScreen mainScreen].bounds.size.width * 9/16) + GK_SAFEAREA_BTM, self.view.bounds.size.width, self.view.bounds.size.height - 64.0) segmentStyle:style titles:self.titles parentViewController:self delegate:self];

    [self.view addSubview:_scrollPageView];
    [self.view addSubview:self.playerView];
    [self doInitPlayerNotication];
    self.sec = 0;
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {

    if ([touch.view isKindOfClass:[UIButton class]]) {
        return NO;
    }
    return YES;
}

- (void)setPlayerUIWithUrl:(NSString *)videoUrl {
    self.player = [[NELivePlayerController alloc] initWithContentURL:[NSURL URLWithString:videoUrl] error:nil];
    self.player.view.frame = self.playerView.bounds;
    [self.playerView addSubview:self.player.view];
    [self.player.view addSubview:self.bottomView];
    [self.player.view addSubview:self.popButton];
    [self.player.view addSubview:self.popButtonBig];
    [self.player.view addSubview:self.returnBUtton];
    
    self.view.autoresizesSubviews = YES;
    [self.player setBufferStrategy:NELPLowDelay]; // 直播低延时模式
    [self.player setShouldAutoplay:YES]; // 设置prepareToPlay完成后是否自动播放
    [self.player setHardwareDecoder:true]; // 设置解码模式，是否开启硬件解码
    [self.player setPauseInBackground:NO]; // 设置切入后台时的状态，暂停还是继续播放
    [self.player setPlaybackTimeout:15 *1000]; // 设置拉流超时时间
    [self.player prepareToPlay];
    [self.player play];
    
    [self.player setScalingMode:NELPMovieScalingModeFill]; // 设置画面显示模式，默认原始大小
    
    /* 这里一定要打开主播放器的sei */
    [self.player setOpenReceiveSyncData:YES];
    
//    [self.player setSyncTimestampListenerWithIntervalMS:500 callback:^(NSTimeInterval realTime) {
//        NSLog(@"当前时间戳：[%f]", realTime);
//        NSTimeInterval durationTime = weakSelf.player.duration;
//        if (!weakSelf.progressSilderTouching) {
//            weakSelf.slider.value = realTime/durationTime;
//        }
//        weakSelf.timeLabel.text = [NSString stringWithFormat:@"%@/%@",[weakSelf timeformatFromSeconds:realTime],[weakSelf timeformatFromSeconds:durationTime]];
//    }];
    
    self.durrTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(currTime) userInfo:nil repeats:YES];
        
//    [self.player setAutoSwitchDefinition:NO];
//    [self.player setBufferStrategy:NELPAntiJitter]; // 点播抗抖动
}

- (void)currTime {
    self.sec ++;
    NSTimeInterval durationTime = self.player.duration;
    NSString *secTr = [NSString stringWithFormat:@"%d",self.sec];
    
    self.slider.value = secTr.floatValue/durationTime;
    self.timeLabel.text = [NSString stringWithFormat:@"%@/%@",[self timeformatFromSeconds:self.sec],[self timeformatFromSeconds:durationTime]];
}

#pragma ZJScrollPageViewDelegate 代理方法
- (NSInteger)numberOfChildViewControllers {
    return self.titles.count;
}

- (UIViewController<ZJScrollPageViewChildVcDelegate> *)childViewController:(UIViewController<ZJScrollPageViewChildVcDelegate> *)reuseViewController forIndex:(NSInteger)index {
    UIViewController<ZJScrollPageViewChildVcDelegate> *childVc = reuseViewController;
    
    if (!childVc) {
        if (index == 0) {
            childVc = [[PlayInfoViewController alloc] init];
            PlayInfoViewController *playInfoVc = (PlayInfoViewController *)childVc;
            [playInfoVc sendPlayInfo:self.playInfo];
        } else {
            childVc = [[PlayChatViewController alloc] init];
            PlayChatViewController *playChatVc = (PlayChatViewController *)childVc;
            [playChatVc sendPlayInfo:self.playInfo];
        }
    }
    return childVc;
}

- (BOOL)shouldAutomaticallyForwardAppearanceMethods {
    return NO;
}

- (void)hideProgress {
    self.bottomView.hidden = YES;
    self.popButton.hidden = YES;
    self.popButtonBig.hidden = YES;
    self.bgView.hidden = YES;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[UIApplication sharedApplication] setStatusBarHidden:NO];
}

- (void)viewDidDisappear:(BOOL)animated {
//    [self.aliPlayer stop];
//    [self.aliPlayer destroy];
    [self.player shutdown];
    self.player = nil;
    [self.timer invalidate];
    self.timer = nil;
    
    self.durrTimer = nil;
    [self.durrTimer invalidate];
}

- (void)preparePlayWithInfo:(NSDictionary *)dic {
    
    self.playInfo = [NSDictionary dictionaryWithDictionary:dic];
    NSLog(@"---------------------%@",self.playInfo);
    
    NSString *status = [NSString stringWithFormat:@"%@",self.playInfo[@"status"]];
    if ([status isEqualToString:@"1"]) {
        self.slider.hidden = YES;
        self.timeLabel.hidden = YES;

        self.titles = @[@"介绍",
        @"聊天",
        ];
        self.pauseButton.hidden = YES;
        self.bgView.hidden = YES;
    }else {
        self.titles = @[@"介绍",
        ];
    }
    
    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"https://ahj-jiaoyu-test.oss-cn-beijing.aliyuncs.com/%@",self.playInfo[@"cover"]]]];
    self.playerImage.image = [UIImage imageWithData:data];
    
    NSString *price = self.playInfo[@"price"];
    NSString *buy_status = [NSString stringWithFormat:@"%@",self.playInfo[@"price"]];
    NSString *videoUrl = status.integerValue == 2 ? self.playInfo[@"recordUrl"] : self.playInfo[@"pullUrl"];
    NSString *apply_status = [NSString stringWithFormat:@"%@",self.playInfo[@"apply_status"]];
    if (kStringIsEmpty(videoUrl) == NO) {
        if (price.doubleValue == 0.00 || [buy_status isEqual:@"1"]) {
//            AVPUrlSource *urlSource = [[AVPUrlSource alloc]urlWithString:videoUrl];
//            [self.aliPlayer setUrlSource:urlSource];
//            [self.aliPlayer prepare];
//            [self.aliPlayer setAutoPlay:YES];
            if (![status isEqual:@"0"]) {
                [self setPlayerUIWithUrl:videoUrl];
            }
        }else {
            self.activityIndicator.hidden = YES;
            self.returnBUtton.hidden = YES;
        }
        
        self.playerName.text = self.playInfo[@"title"];
        NSLog(@"+++++++++++++++++%@",status);
        if ([status isEqual:@"0"]) {
            self.playerView.hidden = YES;
            self.player.view.hidden = YES;
            self.playerImage.hidden = NO;
            NSString *time = [NSString stringWithFormat:@"%@",self.playInfo[@"beginTime"]];
            self.playerTime.text = [NSString stringWithFormat:@"开始时间:%@",time];
            
            [self.playerBackView addSubview:self.popButton];
            [self.playerBackView addSubview:self.popButtonBig];
        }else if ([status isEqual:@"2"])  {
            self.playerView.hidden = YES;
            self.player.view.hidden = YES;
            self.playerImage.hidden = NO;
            self.playerTime.text = @"直播已结束";
            
            [self.playerBackView addSubview:self.popButton];
            [self.playerBackView addSubview:self.popButtonBig];
        }
        else {
            
            if (price.doubleValue == 0.00) {
                self.playerView.hidden = NO;
                self.player.view.hidden = NO;
                self.playerImage.hidden = YES;
                
                // 3S之后隐藏进度条
                self.timer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(hideProgress) userInfo:nil repeats:YES];
                
                [self.player.view addSubview:self.popButton];
                [self.player.view addSubview:self.popButtonBig];
            }else {
                if ([buy_status isEqual:@"1"]) {
                    self.playerView.hidden = NO;
                    self.player.view.hidden = NO;
                    self.playerImage.hidden = YES;
                    
                    // 3S之后隐藏进度条
                    self.timer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(hideProgress) userInfo:nil repeats:YES];
                    
                    
                    [self.player.view addSubview:self.popButton];
                    [self.player.view addSubview:self.popButtonBig];
                }else {
                    self.playerView.hidden = YES;
                    self.player.view.hidden = YES;
                    self.playerImage.hidden = NO;
                    
                    [self.playerBackView addSubview:self.popButton];
                    [self.playerBackView addSubview:self.popButtonBig];
                }
            }
        }
    }else {
        self.playerView.hidden = YES;
        self.player.view.hidden = YES;
        self.playerImage.hidden = NO;
        self.playerName.text = @"直播已结束";
        
        [self.playerBackView addSubview:self.popButton];
        [self.playerBackView addSubview:self.popButtonBig];
    }
}

- (void)back:(UIButton *)btn {
    if (self.screenButtonBig.selected || self.screenButton.selected) {
        [self fullScreen:self.screenButton];
    }else {
        if([self.delegate respondsToSelector:@selector(BackButtonDelegate:)]){
            [self.delegate BackButtonDelegate:btn];
        }
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

- (void)doInitPlayerNotication {
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(NELivePlayerDidPreparedToPlay:)
                                                 name:NELivePlayerDidPreparedToPlayNotification
                                               object:_player];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(NELivePlayerPlaybackStateChanged:)
                                                 name:NELivePlayerPlaybackStateChangedNotification
                                               object:_player];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(NeLivePlayerloadStateChanged:)
                                                 name:NELivePlayerLoadStateChangedNotification
                                               object:_player];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(NELivePlayerPlayBackFinished:)
                                                 name:NELivePlayerPlaybackFinishedNotification
                                               object:_player];
//
//    [[NSNotificationCenter defaultCenter] addObserver:self
//                                             selector:@selector(NELivePlayerFirstVideoDisplayed:)
//                                                 name:NELivePlayerFirstVideoDisplayedNotification
//                                               object:_player];
//
//    [[NSNotificationCenter defaultCenter] addObserver:self
//                                             selector:@selector(NELivePlayerFirstAudioDisplayed:)
//                                                 name:NELivePlayerFirstAudioDisplayedNotification
//                                               object:_player];
//
//    [[NSNotificationCenter defaultCenter] addObserver:self
//                                             selector:@selector(NELivePlayerReleaseSuccess:)
//                                                 name:NELivePlayerReleaseSueecssNotification
//                                               object:nil];
//
//    [[NSNotificationCenter defaultCenter] addObserver:self
//                                             selector:@selector(NELivePlayerSeekComplete:)
//                                                 name:NELivePlayerMoviePlayerSeekCompletedNotification
//                                               object:_player];
}

- (void)NELivePlayerDidPreparedToPlay:(NSNotification*)notification {
    NSLog(@"[NELivePlayer Demo] 收到 NELivePlayerPlaybackStateChangedNotification 通知");
    NELPMovieLoadState nelpLoadState = _player.loadState;
    if (nelpLoadState == NELPMovieLoadStatePlayable)
    {
        NSLog(@"播放");
//        _controlView.isBuffing = YES;
        self.activityIndicator.hidden = YES;
        self.returnBUtton.hidden = YES;
    }
}

- (void)NELivePlayerPlaybackStateChanged:(NSNotification*)notification {
    NSLog(@"[NELivePlayer Demo] 收到 NELivePlayerPlaybackStateChangedNotification 通知");
    NELPMovieLoadState nelpLoadState = _player.loadState;
    if (nelpLoadState == NELPMovieLoadStatePlayable)
    {
        NSLog(@"播放");
//        _controlView.isBuffing = YES;
        self.activityIndicator.hidden = YES;
        self.returnBUtton.hidden = YES;
    }
}

- (void)NeLivePlayerloadStateChanged:(NSNotification*)notification {
    NSLog(@"[NELivePlayer Demo] 收到 NELivePlayerLoadStateChangedNotification 通知");
    
    NELPMovieLoadState nelpLoadState = _player.loadState;
    
    if (nelpLoadState == NELPMovieLoadStatePlaythroughOK)
    {
        NSLog(@"finish buffering");
//        _controlView.isBuffing = NO;
        self.activityIndicator.hidden = YES;
        self.returnBUtton.hidden = YES;
    }
    else if (nelpLoadState == NELPMovieLoadStateStalled)
    {
        NSLog(@"begin buffering");
//        _controlView.isBuffing = YES;
        self.activityIndicator.hidden = NO;
        self.returnBUtton.hidden = YES;
    }
    else if (nelpLoadState == NELPMovieLoadStatePlayable)
    {
        NSLog(@"播放");
//        _controlView.isBuffing = YES;
        self.activityIndicator.hidden = YES;
        self.returnBUtton.hidden = YES;
    }
}

- (void)NELivePlayerPlayBackFinished:(NSNotification*)notification {

    __weak typeof(self) weakSelf = self;
    switch ([[[notification userInfo] valueForKey:NELivePlayerPlaybackDidFinishReasonUserInfoKey] intValue])
    {
        case NELPMovieFinishReasonPlaybackError:
        {
            weakSelf.activityIndicator.hidden = NO;
            weakSelf.returnBUtton.hidden = NO;
            [self.durrTimer invalidate];
            self.durrTimer = nil;
            break;
        }
            
        case NELPMovieFinishReasonUserExited:
            break;
            
        default:
            break;
    }
}

#pragma mark - 重试
- (void)returnAction {
    
    self.returnBUtton.hidden = YES;
    [self.player shutdown];
    self.player = nil;
    [self.player.view removeFromSuperview];
    NSString *status = [NSString stringWithFormat:@"%@",self.playInfo[@"status"]];
    NSString *videoUrl = status.integerValue == 2 ? self.playInfo[@"recordUrl"] : self.playInfo[@"pullUrl"];
    [self setPlayerUIWithUrl:videoUrl];
    
    [self.durrTimer invalidate];
    self.durrTimer = nil;
    self.sec = 0;
    self.durrTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(currTime) userInfo:nil repeats:YES];
}

/**
 @brief 播放器事件回调
 @param player 播放器player指针
 @param eventType 播放器事件类型，@see AVPEventType
 */
//-(void)onPlayerEvent:(AliPlayer*)player eventType:(AVPEventType)eventType {
//    switch (eventType) {
//        case AVPEventPrepareDone: {
//            // 准备完成
//        }
//            break;
//        case AVPEventAutoPlayStart:
//            // 自动播放开始事件
//            self.activityIndicator.hidden = YES;
//            break;
//        case AVPEventFirstRenderedStart:
//            // 首帧显示
//            break;
//        case AVPEventCompletion:
//            // 播放完成
//            break;
//        case AVPEventLoadingStart:
//            // 缓冲开始
//            self.activityIndicator.hidden = NO;
//            break;
//        case AVPEventLoadingEnd:
//            // 缓冲完成
//            self.activityIndicator.hidden = YES;
//            break;
//        case AVPEventSeekEnd:
//            // 跳转完成
//            break;
//        case AVPEventLoopingStart:
//            // 循环播放开始
//            break;
//        default:
//            break;
//    }
//}

- (void)progressTouchDown:(id)sender
{
    self.progressSilderTouching = YES;
}

- (void)progressTouchUp:(id)sender
{
    NSTimeInterval currentTime = self.slider.value;
    NSTimeInterval durationTime = self.player.duration;
    self.progressSilderTouching = NO;
//    self.pla
    [self.player setCurrentPlaybackTime:currentTime*durationTime];
    self.sec = self.slider.value*self.player.duration;
//    [_aliPlayer seekToTime:currentTime*durationTime seekMode:self.aliPlayer.duration < 300000 ? AVP_SEEKMODE_ACCURATE : AVP_SEEKMODE_INACCURATE];
    self.timeLabel.text = [NSString stringWithFormat:@"%@/%@",[self timeformatFromSeconds:self.slider.value*self.player.duration],[self timeformatFromSeconds:durationTime]];
}

- (NSString *)timeformatFromSeconds:(NSInteger)seconds {
    //format of hour
//    seconds = seconds/1000;
    //format of minute
    NSString *str_minute = [NSString stringWithFormat:@"%02ld", (long) seconds / 60];
    //format of second
    NSString *str_second = [NSString stringWithFormat:@"%02ld", (long) seconds % 60];
    //format of time
    NSString *format_time = nil;
    format_time = [NSString stringWithFormat:@"%@:%@", str_minute, str_second];
    return format_time;
}

#pragma mark - 隐藏状态栏
- (void)hideProessBar:(UIGestureRecognizer *)tap {
    if (tap.numberOfTouches == 1) {
        [self.timer invalidate];
        self.timer = nil;
        
        // 3S之后隐藏进度条
        self.timer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(hideProgress) userInfo:nil repeats:YES];
        self.bottomView.hidden = !self.bottomView.hidden;
        NSString *status = [NSString stringWithFormat:@"%@",self.playInfo[@"status"]];
        if (![status isEqualToString:@"1"]) {
            self.bgView.hidden = !self.bgView.hidden;
        }
        self.popButton.hidden = !self.popButton.hidden;
        self.popButtonBig.hidden = !self.popButtonBig.hidden;
    }
}
     
#pragma mark - 播放暂停
- (void)TapPlayAndStop:(UIGestureRecognizer *)tap {
    NSString *status = [NSString stringWithFormat:@"%@",self.playInfo[@"status"]];
    if (![status isEqualToString:@"1"]) {
        [self pauseAndStart:self.pauseButton];
    }
}

#pragma mark -
//- setsync
//- (void)onCurrentPositionUpdate:(AliPlayer*)player position:(int64_t)position {
//
//    NSTimeInterval currentTime = position;
//    NSTimeInterval durationTime = self.aliPlayer.duration;
//    if (!self.progressSilderTouching) {
//        self.slider.value = currentTime/durationTime;
//    }
//    self.timeLabel.text = [NSString stringWithFormat:@"%@/%@",[self timeformatFromSeconds:currentTime],[self timeformatFromSeconds:durationTime]];
//}

#pragma mark - 播放暂停按钮
- (void)pauseAndStart:(UIButton *)btn {
    btn.selected = !btn.selected;
    if (btn.selected) {
        [self.durrTimer setFireDate:[NSDate distantFuture]];
        [self.player setMute:YES];
        [self.player pause];
    }else {
        [self.durrTimer setFireDate:[NSDate date]];
        [self.player setMute:NO];
        [self.player play];
    }
}

#pragma mark - 清晰度选择
- (void)clarityAction:(UIButton *)btn {
    [self.timer invalidate];
    self.timer = nil;
}

- (void)claritySelected:(UIButton *)btn {
    self.bottomView.hidden  = YES;
}

#pragma maek - 全屏
- (void)fullScreen:(UIButton *)btn {
    [self.view endEditing:YES];
    btn.selected = !btn.selected;
    
    if (btn.selected) {
        [UIView animateWithDuration:0.3 animations:^{
            CGAffineTransform at = CGAffineTransformMakeRotation(M_PI/2);
            [self.playerView setTransform:at];
            self.playerView.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height);
            self.player.view.frame = self.playerView.bounds;
            [[UIApplication sharedApplication] setStatusBarHidden:YES];
            self.bottomView.frame = CGRectMake(0, [UIScreen mainScreen].bounds.size.width - 40, [UIScreen mainScreen].bounds.size.height, 40);
            self.slider.frame = CGRectMake(100, 10, [UIScreen mainScreen].bounds.size.height - 210, 20);
            self.screenButton.frame = CGRectMake([UIScreen mainScreen].bounds.size.height - 80, 10, 30, 20);
            self.screenButtonBig.frame = CGRectMake([UIScreen mainScreen].bounds.size.height - 80, 0, 50, 50);
            self.bgView.frame = CGRectMake([UIScreen mainScreen].bounds.size.height/2 - 20, [UIScreen mainScreen].bounds.size.width/2 - 20, 40, 40);
            self.activityIndicator.frame = CGRectMake(([UIScreen mainScreen].bounds.size.height - 50)/2, 100, 50, 50);
            self.returnBUtton.frame = CGRectMake(([UIScreen mainScreen].bounds.size.height - 100)/2, 120, 100, 50);
        }];
        
    }else {
        [UIView animateWithDuration:0.3 animations:^{
            CGAffineTransform at = CGAffineTransformMakeRotation(180 *M_PI / 90);
            [self.playerView setTransform:at];
            self.playerView.frame = CGRectMake(0, GK_SAFEAREA_BTM, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.width * 9/16);
            self.player.view.frame = self.playerView.bounds;
            [[UIApplication sharedApplication] setStatusBarHidden:NO];
            self.bottomView.frame = CGRectMake(0, CGRectGetHeight(self.playerView.frame) - 40, CGRectGetWidth(self.playerView.frame), 40);
            self.slider.frame = CGRectMake(100, 10, [UIScreen mainScreen].bounds.size.width - 210, 20);
            self.screenButton.frame = CGRectMake([UIScreen mainScreen].bounds.size.width - 40, 10, 30, 20);
            self.bgView.frame = CGRectMake([UIScreen mainScreen].bounds.size.width/2 - 20, ([UIScreen mainScreen].bounds.size.width * 9/16)/2 - 20, 40, 40);
            self.activityIndicator.frame = CGRectMake(([UIScreen mainScreen].bounds.size.width - 50)/2, 80, 50, 50);
            self.returnBUtton.frame = CGRectMake(([UIScreen mainScreen].bounds.size.width - 100)/2, 120, 100, 50);
        }];
    }
}

#pragma mark - 懒加载
//- (AVPSeekMode)seekMode {
////    if (self.aliPlayer.duration < 300000) {
////        return AVP_SEEKMODE_ACCURATE;
////    }
////    return AVP_SEEKMODE_INACCURATE;
//}

//- (AliPlayer *)aliPlayer{
//    if (!_aliPlayer) {
//        _aliPlayer = [[AliPlayer alloc] init];
//        _aliPlayer.scalingMode =  AVP_SCALINGMODE_SCALETOFILL;
//        _aliPlayer.playerView = self.playerView;
//        _aliPlayer.delegate = self;
//        _aliPlayer.rate = 1;
//        self.aliPlayer.loop = true;
//    }
//    return _aliPlayer;
//}

- (UIView *)playerView {
    if (!_playerView) {
        _playerView = [[UIView alloc]initWithFrame:CGRectMake(0, GK_SAFEAREA_BTM, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.width * 9/16)];
        _playerView.backgroundColor = [UIColor whiteColor];
    }
    return _playerView;
}

- (UIImageView *)playerImage {
    if (!_playerImage) {
        _playerImage = [[UIImageView alloc]initWithFrame:CGRectMake(0, GK_SAFEAREA_BTM, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.width * 9/16)];
        _playerImage.hidden = YES;
        _playerImage.userInteractionEnabled = YES;
    }
    return _playerImage;
}

- (UIView *)playerBackView {
    if (!_playerBackView) {
        _playerBackView = [[UIView alloc] initWithFrame:self.playerImage.bounds];
        _playerBackView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.3f];
        _playerBackView.userInteractionEnabled = YES;
    }
    return _playerBackView;
}

- (UILabel *)playerName {
    if (!_playerName) {
        _playerName = [[UILabel alloc] initWithFrame:CGRectMake(0, [UIScreen mainScreen].bounds.size.width * 9/32, [UIScreen mainScreen].bounds.size.width, 30)];
        _playerName.textColor = [UIColor whiteColor];
        _playerName.font = [UIFont boldSystemFontOfSize:20];
        _playerName.textAlignment = NSTextAlignmentCenter;
    }
    return _playerName;
}

- (UILabel *)playerTime {
    if (!_playerTime) {
        _playerTime = [[UILabel alloc] initWithFrame:CGRectMake(0, ([UIScreen mainScreen].bounds.size.width * 9/16) - 30, [UIScreen mainScreen].bounds.size.width, 30)];
        _playerTime.textColor = [UIColor whiteColor];
        _playerTime.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.3];
        _playerTime.textAlignment = NSTextAlignmentRight;
    }
    return _playerTime;
}

- (UIView *)bottomView {
    if (!_bottomView) {
        _bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetHeight(self.playerView.frame) - 40, [UIScreen mainScreen].bounds.size.width, 40)];
        _bottomView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.3f];
    }
    return _bottomView;
}

- (UIButton *)bgView {
    if (!_bgView) {
        _bgView = [UIButton buttonWithType:UIButtonTypeCustom];
        _bgView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];
        _bgView.frame = CGRectMake([UIScreen mainScreen].bounds.size.width/2 - 20, ([UIScreen mainScreen].bounds.size.width * 9/16)/2 - 20, 40, 40);
        _bgView.layer.masksToBounds = YES;
        _bgView.layer.cornerRadius = 20;
        [_bgView addTarget:self action:@selector(pauseAndStart:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _bgView;
}

- (UIButton *)pauseButton {
    if (!_pauseButton) {
        _pauseButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _pauseButton.frame = CGRectMake(5, 5, 30, 30);
        [_pauseButton setImage:[UIImage imageNamed:@"avcPause"] forState:UIControlStateNormal];
        [_pauseButton setImage:[UIImage imageNamed:@"avcPlayIcon"] forState:UIControlStateSelected];
        [_pauseButton addTarget:self action:@selector(pauseAndStart:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _pauseButton;
}

- (UILabel *)timeLabel {
    if (!_timeLabel) {
        _timeLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 5, 80, 30)];
        _timeLabel.textColor = [UIColor whiteColor];
        _timeLabel.font = [UIFont systemFontOfSize:12];
    }
    return _timeLabel;
}

- (LivePlaySlider *)slider {
    if (!_slider) {
        _slider = [[LivePlaySlider alloc] init];
        _slider.frame = CGRectMake(100, 10, [UIScreen mainScreen].bounds.size.width - 210, 20);
        [_slider addTarget:self action:@selector(progressTouchDown:) forControlEvents:UIControlEventTouchDown];
        [_slider addTarget:self action:@selector(progressTouchUp:) forControlEvents:UIControlEventTouchUpInside];
        [_slider addTarget:self action:@selector(progressTouchUp:) forControlEvents:UIControlEventTouchCancel];
        [_slider addTarget:self action:@selector(progressTouchUp:) forControlEvents:UIControlEventTouchUpOutside];
        
        /*  修改进度条的样式  */
        [_slider setThumbImage:[UIImage imageNamed:@"slide_image"] forState:UIControlStateNormal];
        _slider.layer.masksToBounds = YES;
        _slider.layer.cornerRadius = 3;
        _slider.minimumTrackTintColor = UIColorFromRGB(0xff1296db);
        _slider.maximumTrackTintColor = [[UIColor whiteColor] colorWithAlphaComponent:0.4];
    }
    return _slider;
}

- (UIButton *)screenButton {
    if (!_screenButton) {
        _screenButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_screenButton setImage:[UIImage imageNamed:@"alivc_fullScreen"] forState:UIControlStateNormal];
        _screenButton.frame = CGRectMake([UIScreen mainScreen].bounds.size.width - 40, 10, 30, 20);
        [_screenButton addTarget:self action:@selector(fullScreen:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _screenButton;
}

- (UIButton *)screenButtonBig {
    if (!_screenButtonBig) {
        _screenButtonBig = [UIButton buttonWithType:UIButtonTypeCustom];
        _screenButtonBig.frame = CGRectMake([UIScreen mainScreen].bounds.size.width, 0, 50, 50);
        [_screenButtonBig addTarget:self action:@selector(fullScreen:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _screenButtonBig;
}

- (UIButton *)popButton {
    if (!_popButton) {
        _popButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_popButton setImage:[UIImage imageNamed:@"avcBackIcon"] forState:UIControlStateNormal];
        _popButton.frame = CGRectMake(10, GK_SAFEAREA_TOP + 20, 30, 40);
        [_popButton addTarget:self action:@selector(back:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _popButton;
}

- (UIActivityIndicatorView *)activityIndicator {
    if (!_activityIndicator) {
        _activityIndicator = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:(UIActivityIndicatorViewStyleGray)];
        //设置小菊花的frame
        _activityIndicator.frame= CGRectMake(([UIScreen mainScreen].bounds.size.width - 50)/2, 80, 50, 50);
        //设置小菊花颜色
        _activityIndicator.color = [[UIColor blackColor] colorWithAlphaComponent:0.3];
//        _activityIndicator.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.3];
        //设置背景颜色
        //刚进入这个界面会显示控件，并且停止旋转也会显示，只是没有在转动而已，没有设置或者设置为YES的时候，刚进入页面不会显示
        _activityIndicator.hidesWhenStopped = NO;
        
        [_activityIndicator startAnimating];
    }
    return _activityIndicator;
}

- (UIButton *)returnBUtton {
    if (!_returnBUtton) {
        _returnBUtton = [[UIButton alloc] initWithFrame:CGRectMake(([UIScreen mainScreen].bounds.size.width - 100)/2, 120, 100, 50)];
        [_returnBUtton setTitle:@"重试" forState:UIControlStateNormal];
        _returnBUtton.hidden = YES;
        [_returnBUtton addTarget:self action:@selector(returnAction) forControlEvents:UIControlEventTouchUpInside];
        _returnBUtton.backgroundColor = UIColorFromRGB(0xFF1a73e8);
    }
    return _returnBUtton;
}

- (UIButton *)popButtonBig {
    if (!_popButtonBig) {
        _popButtonBig = [UIButton buttonWithType:UIButtonTypeCustom];
        _popButtonBig.frame = CGRectMake(0, 0, 80, 80);
        [_popButtonBig addTarget:self action:@selector(back:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _popButtonBig;
}

- (void)dealloc {
    [self.timer invalidate];
    self.timer = nil;
    [self.player shutdown];
    self.player = nil;
    
    self.durrTimer = nil;
    [self.durrTimer invalidate];
//    [self.aliPlayer destroy];
}
@end
